package cn.edu.gcu.PraticalTraining.controller;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.gcu.PraticalTraining.domain.User;
import cn.edu.gcu.PraticalTraining.service.UserService;

@Controller
public class MainController {
	private static final Logger log = LoggerFactory.getLogger(MainController.class);

	@Autowired
	private UserService userService;

	@RequestMapping("/")
	public ModelAndView index() {
		return new ModelAndView("/index");
	}

	@GetMapping("/login")
	public ModelAndView login() {
		return new ModelAndView("login");
	}

	@PostMapping("/login")
	public ModelAndView login(String username, String password, HttpSession httpSession) {
		User user = userService.findByUsername(username);
		if (user != null && user.getPassword().equals(password)) {
			httpSession.setAttribute("user", user);
			return new ModelAndView("redirect:/propaganda/");
		} else {
			ModelAndView mav = new ModelAndView("/login");
			mav.addObject("msg", "用户名或密码错误");
			return mav;
		}
	}
	
	/**
	 * 注销用户
	 * @param httpSession
	 * @return
	 */
	@RequestMapping("/logout")
	public ModelAndView logout(HttpSession httpSession){
		if(httpSession.getAttribute("user") != null){
			httpSession.removeAttribute("user");
		}
		return new ModelAndView("redirect:/login");
	}
}
